<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import { searchService, getRecordByIdService, getCityList, getCountyList, getRecord, getRecordField } from '@/api/record'
import { useRouter, useRoute } from 'vue-router';
import { throttle } from 'lodash'

const router = useRouter();
const route = useRoute();
const recordId = ref(0)
const isSearch = ref(true)


const searchRecordsList = ref([])
const record = ref(
  {
    id: '',
    name: '',
    comment: '',
    province: '',
    city: '',
    county: '',
    categoryList: [
      {
        id: '',
        imgUrl: ''
      }
    ]
  }
)
const searchText = ref()
// 生命周期
onMounted(() => {
  // 然后你就可以在组件中使用 searchText 了
  // searchText.value = router.currentRoute.value.params.searchText;
  searchText.value = route.query.searchText
  console.log(searchText.value)
});
watch(searchText, () => {
  isSearch.value = true
  search(searchText)
})
// 搜索
const search = throttle(async (searchText) => {
  if (!searchText) {
    return
  }
  isSearch.value = true
  const fn = async (searchText) => {
    const res = await searchService(searchText.value)
    searchRecordsList.value = res.data.data
    console.log(searchRecordsList.value)
  }
  fn(searchText)
}, 1000)

// 分类名字数组
const categoryStr = ['', '疆域', '星野', '学宫', '城池', '县署', '水利', '祠庙', '山水名胜', '其他']

// 返回到上一级
const goBack = () => {
  router.go(-1)
}
// 目录数据集合
const catalogList = ref([
  // 省级
  {
    id: null,
    isLeaf: false,
    name: '四川省',
    children: [
      {
        id: null,
        isLeaf: false,
        name: '查看省志',
        children: []
      }
    ]

  },
  {
    name: '重庆市',
    id: null,
    isLeaf: false,
    children: [{
      id: null,
      isLeaf: false,
      name: '查看市志',
      children: []
    }]
  },
])

// 目录绑定关系
const defaultProps = {
  children: 'children',
  label: 'name',
  isLeaf: 'isLeaf',
}

// 跳转到查看舆图
const showCategory = (id) => {
  router.push({ path: '/record/category', query: { id, recordId: recordId.value } })
}

// 查看单个方志
const lookRecord = async (id) => {
  recordId.value = id
  isSearch.value = false
  const res = await getRecordByIdService(id);
  record.value = res.data.data
  console.log(record.value)

  record.value.categoryList = Object.keys(res.data.data.firstUrlMap
  ).map(key => ({ id: key, imgUrl: res.data.data.firstUrlMap[key] }));
}


// // 懒加载节点
const loadNode = async (node, resolve) => {
  const nodeName = node.data.name
  if (node.data.id) {
    console.log(node.data.id)
    lookRecord(node.data.id)
    return resolve([])
  }

  // 默认
  if (node.level === 0) {

    return resolve(catalogList.value)
  }
  // 如果点击的是四川省 成都市
  if (node.level === 1) {
    const target = catalogList.value.find(level1 => level1.name === nodeName)

    if (target.children.length > 1) {
      return resolve(target.children)
    }
    const res = await getCityList(nodeName)
    target.children = res.data.data

    if (nodeName === '四川省') {
      target.children.push({
        level: nodeName,
        isLeaf: false,
        name: '查看省志',
        children: []
      })
    }
    else {
      target.children.push({
        level: nodeName,
        isLeaf: false,
        name: '查看市志',
        children: []
      })
    }

    return resolve(target.children)
  }
  if (node.level === 2) {
    let target
    // 遍历第一级省级目录
    for (let i = 0; i < catalogList.value.length; i++) {
      const item = catalogList.value[i];
      target = item.children.find(item => item.name === nodeName);
      if (target) {
        // 找到了符合条件的对象，可以在这里进行处理
        break; // 终止循环
      }
    }

    if (!Array.isArray(target.children)) {
      if (target.children) {
        target.children = [target.children]
      }
      target.children = []
    }
    if (target.children.length > 0) {
      return resolve(target.children)
    }

    // 如果查看省志
    if (node.data.level) {

      const res = await getRecord(node.data.level, node.level - 1)
      if (!res.data.data) {
        return resolve([])
      }
      target.children = res.data.data
      console.log(target.children)
      return resolve(target.children)
    }

    const res = await getCountyList(nodeName)
    target.children = res.data.data

    if (nodeName !== '查看市志' && nodeName !== '查看省志')
      target.children.push({
        level: nodeName,
        name: '查看市志',
        isLeaf: 'false'
      })
    return resolve(target.children)
  }
  if (node.level === 3) {
    let target
    // 遍历第一级省级目录
    for (let i = 0; i < catalogList.value.length; i++) {
      const cityList = catalogList.value[i].children
      // 遍历第二级市级目录
      for (let i = 0; i < cityList.length; i++) {
        let countyList = cityList[i].children
        if (!countyList) {
          continue
        }
        target = countyList.find(item => item.name === nodeName)
        if (target) {
          // 找到了符合条件的对象，可以在这里进行处理
          break; // 终止循环
        }
      }
      if (target) {
        // 找到了符合条件的对象，可以在这里进行处理
        break; // 终止循环
      }
    }
    if (!Array.isArray(target.children)) {
      if (target.children) {
        target.children = [target.children]
      }
      target.children = []
    }
    if (target.children.length > 0) {
      return resolve(target.children)
    }
    // 如果查看市志
    if (node.data.level) {

      const res = await getRecord(node.data.level, node.level - 1)
      if (!res.data.data) {
        return resolve([])
      }
      target.children = res.data.data
      console.log(target.children)
      return resolve(target.children)
    }

    const res = await getRecord(nodeName, node.level)

    target.children = res.data.data

    return resolve(target.children)
  }



}
</script>

<template>
  <!-- 返回 -->
  <el-button @click="goBack" class="goBackBtn" type="primary">
    <el-icon class="el-icon--right">
      <ArrowLeftBold />
    </el-icon> 返回
  </el-button>
  <div class="container">
    <!-- 目录 -->
    <div class="catalogBox">
      <el-input v-model="searchText" style="width: 175px" placeholder="请输入" />
      <!-- accordion -->
      <el-tree ref="treeRef" style="max-width: 175px" empty-text="暂无数据" accordion :load="loadNode" lazy
        :props="defaultProps" highlight-current="true" />
    </div>

    <!-- 方志区域 -->
    <div class="left" v-show="!isSearch">
      <div class="titleBox">
        <h2 class="title">{{ record.name }}</h2>
      </div>

      <div class="textBox">

        <p class="text">
          {{ }}
          {{ record.comment }}
        </p>
      </div>
    </div>
    <div class="left" v-show="isSearch">
      <div class="search-record-list">
        <div class="search-record-item" @click="lookRecord(item.id)" v-for="(item ) in searchRecordsList" :key=item.id>
          <span> {{ item.name }} </span><span> {{ item.province + item.city + item.county }}
          </span>
        </div>
      </div>
    </div>
    <!-- 分类图区域 -->
    <div class="right" :style="{ backgroundImage: `url(${record.categoryList[0].imgUrl})` }">

      <div class="mapCategoryBox">

        <div class="categoryItemBox" v-for="(item, index) in record.categoryList" :key="index">
          <img :src="item.imgUrl" alt="">
          <div class="shadowBox" @click="showCategory(item.id)">
            {{ categoryStr[item.id] }}
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
// 返回
.goBackBtn {
  width: 40px;
  height: 20px;
  font-size: 10px;
  margin-top: 10px;
  margin-left: 10px;
  padding: 0;
  padding-right: 10px;
}

// 舆图展示的盒子
.container {
  width: 100%;
  display: flex;
  height: 350px;
  margin: 0px auto;
  margin-top: 10px;
  justify-content: space-evenly;


  // 左边方志区域
  .left {
    width: 40%;
    height: 350px;
    background-color: #efefef;

    .titleBox {
      width: calc(100% - 20px);
      margin: 10px 10px;
      border-bottom: 1px solid #efefef;

      .title {
        padding: 7px;
      }
    }

    .textBox {
      width: auto;
      min-height: 250px;
      padding: 7px;

      .text {
        font-size: 10px
      }
    }

    .search-record-list {
      height: 100%;
      width: 100%;
      overflow-y: scroll;
      padding: 0px 7px;

      .search-record-item {
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        font-size: 10px;
        margin: 5px;
        width: 100%;
        height: 20px;
        border-bottom: 1px #adadad solid;
        transition: all 0.25s ease;
      }

      .search-record-item:hover {
        color: #d1c1aa;
      }

    }
  }

  // 右边分类区域
  .right {
    width: 45%;
    height: 350px;
    display: flex;
    justify-content: center;
    align-items: center;

    .mapCategoryBox {
      padding: 5px;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.3);
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: center;

      .categoryItemBox {
        margin: 2.5px 0px;
        height: 80px;
        width: 30%;
        position: relative;

        img {
          width: 100%;
          height: 100%;
        }

        .shadowBox {
          background-color: rgba(0, 0, 0, 0.4);
          opacity: 1;
          height: 100%;
          width: 100%;
          font-size: 19px;
          color: #efefef;
          position: absolute;
          z-index: 5;
          top: 0;
          transition: all 0.5s ease;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;

        }
      }

      .categoryItemBox:nth-child(4),
      .categoryItemBox:nth-child(5) {
        width: 45%;
      }


    }
  }

  // 目录
  .catalogBox {
    width: 84px;
    height: 100%;
    background-color: #efefef;
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>